package newBee.class1;

/**
 * https://leetcode.cn/problems/sum-of-subarray-minimums/description/
 * 子数组的最小值之和
 * 解题思路：
 * 1.大压小
 */
public class Code04_sumSubarrayMins {
    public static void main(String[] args) {
        int[] arr = {3, 1, 2, 4};
        int ans = sumSubarrayMins(arr);
        System.out.println("ans = " + ans);
    }

    public static int mod = (int) 1e9 + 7;

    public static int sumSubarrayMins(int[] arr) {
        int r = 0, l, n = arr.length;
        long ans = 0;
        int[] stack = new int[n];
        for (int i = 0; i < n; i++) {
            while (r > 0 && arr[stack[r - 1]] >= arr[i]) {
                int k = stack[--r];
                l = r == 0 ? -1 : stack[r - 1];
                // 出栈后，获得最小值范围 (k-l) * (i-k) *arr[k]
                // 也就是  k-l是左范围， i-k是右范围
                // 次数{(k-l)*(i-k)}  *  arr[k]最小值
                ans = ans + ((long) (k - l) * (i - k) * arr[k]) % mod;
            }
            stack[r++] = i;
        }
        while (r > 0) {
            int k = stack[--r];
            l = r == 0 ? -1 : stack[r - 1];
            ans = ans + ((long) (k - l) * (n - k) * arr[k]) % mod;
        }
        return (int) ans;
    }
}
